package com.zhf.demo03.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/10/13 19:05
 */
public class DbUtil {
    private static String jdbcName; //描述驱动信息
    private static String dbUrl;    //描述URL信息
    private static String dbUserName;   //描述用户名
    private static String dbPassword;   //描述密码

    //初始化操作
    static {
        jdbcName="com.mysql.jdbc.Driver";
        dbUrl="jdbc:mysql://localhost:3306/db_web";
        dbUserName="root";
        dbPassword="12345";
        try {
            Class.forName(jdbcName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        return connection;
    }

    /**
     * 关闭连接
     * @param con
     */
    public static void closeResource(Connection con, PreparedStatement psts){
        if (con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (psts!=null){
            try {
                psts.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
